package cn.edu.hqu.cst.android.wzc.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    private int count=0;
    private boolean quit=false;
    private MyServiceBinder myServiceBinder=new MyServiceBinder();
    public MyService() {
    }
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("Service is Binded");
        return myServiceBinder;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service is Created");
        new Thread(() ->
        {
            while (!quit)   {
                try {
                    Thread.sleep(1000);
                }   catch (InterruptedException e)  {
                    e.printStackTrace();
                }
                MyService.this.count++;
            }
        }).start();
//创建新 Thread，如果 service 启动每秒钟 count++，如果 quit 为真则退出
    }
    class MyServiceBinder extends Binder {
        public int getCount(){
            return MyService.this.count;
        }
    }
    @Override
    public boolean onUnbind(Intent intent)
    {
        System.out.println("Service is Unbinded");
        return true;
    }
    public void onDestroy() {
        super.onDestroy();
        quit=true;
        System.out.println("Service is Destoryed");
    }
}